package com.ihunanren.biz.weixin.ao.impl;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.isNullOrEmpty;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ihunanren.biz.result.Result;
import com.ihunanren.biz.result.ResultSupport;
import com.ihunanren.biz.weixin.ao.ISchoolCurriculumAO;
import com.ihunanren.biz.weixin.domain.school.SchoolCurriculum;
import com.ihunanren.common.CalendarUtil;
import com.ihunanren.common.CollectionUtils;
import com.ihunanren.dao.pojo.SchoolCurriculumDefinedDO;
import com.ihunanren.dao.pojo.SchoolCurriculumInfoDO;
import com.ihunanren.dao.weixin.ISchoolCurriculumDefinedDao;
import com.ihunanren.dao.weixin.ISchoolCurriculumInfoDao;

/**
 * @author kalman03
 */
public class SchoolCurriculumAO implements ISchoolCurriculumAO{

	private final static Logger log = LoggerFactory.getLogger(SchoolCurriculumAO.class);
	
	@Autowired
	private ISchoolCurriculumDefinedDao schoolCurriculumDefinedDao;
	@Autowired
	private ISchoolCurriculumInfoDao schoolCurriculumInfoDao;
	
	@Override
	public Result insertStudent(String ip, SchoolCurriculumDefinedDO definedDO) {
		Result result = new ResultSupport(false);
		try {
			checkArgs(definedDO);
			SchoolCurriculumDefinedDO definedDO2 = getByEmail(definedDO.getEmail());
			if(definedDO2 != null){
				result.setDefaultErrorMsg("邮箱已被注册");
				return result;
			}
			SchoolCurriculumDefinedDO definedDO3 = schoolCurriculumDefinedDao.getByDiyName(definedDO.getDiyName());
			if(definedDO3 != null){
				result.setDefaultErrorMsg("接头暗号已被占用");
				return result;
			}
			schoolCurriculumDefinedDao.insertSchoolCurriculumDefinedDO(definedDO);
			result.setSuccess(true);
			result.setDefaultModel(true);
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.insertStudent catch a exception.",e);
		}
		return result;
	}
	
	@Override
	public Result queryAllSchoolCurriculum(String diyName) {
		Result result = new ResultSupport(false);
		try {
			checkArgument(!isNullOrEmpty(diyName));
			SchoolCurriculumDefinedDO definedDO = schoolCurriculumDefinedDao.getByDiyName(diyName);
			if(definedDO != null){
				long definedId = definedDO.getId();
				
				List<SchoolCurriculumInfoDO> infoList = schoolCurriculumInfoDao.getSchoolCurriculumInfo(definedId);
				
				result.setDefaultModel(new SchoolCurriculum(definedDO, infoList));
				result.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.queryAllSchoolCurriculum catch a exception.",e);
		}
		return result;
	}
	
	@Override
	public Result queryAllSchoolCurriculumByDefinedId(long id) {
		Result result = new ResultSupport(false);
		try {
			checkArgument(id>0);
			SchoolCurriculumDefinedDO definedDO = schoolCurriculumDefinedDao.getByDefinedId(id);
			if(definedDO != null){
				long definedId = definedDO.getId();
				
				List<SchoolCurriculumInfoDO> infoList = schoolCurriculumInfoDao.getSchoolCurriculumInfo(definedId);
				
				result.setDefaultModel(new SchoolCurriculum(definedDO, infoList));
				result.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.queryAllSchoolCurriculum catch a exception.",e);
		}
		return result;
	}
	
	@Override
	public Result insertSchoolCurriculumInfo(SchoolCurriculumInfoDO infoDO) {
		Result result = new ResultSupport(false);
		try {
			checkArgs(infoDO,false);
			
			String timeStart = infoDO.getTimeStart();
			String timeEnd = infoDO.getTimeEnd();
			if(isTimeOutOf180Mins(timeStart, timeEnd)){
				result.setDefaultErrorMsg("课时区间选择错误，单节课不能超过180分钟，不能小于30分钟");
				return result;
			}
			
			List<SchoolCurriculumInfoDO> list = schoolCurriculumInfoDao.getSchoolCurriculumInfo(infoDO.getDefinedId());
			if(CollectionUtils.isEmpty(list)){
				schoolCurriculumInfoDao.insertSchoolCurriculumInfo(infoDO);
			}else{
				
				SchoolCurriculumInfoDO db = getSameLessionSection(list, infoDO);
				if(db != null){
					db.setLession(infoDO.getLession());
					db.setRemark(infoDO.getRemark());
					db.setLocation(infoDO.getLocation());
					db.setTeacher(infoDO.getTeacher());
					db.setTimeStart(infoDO.getTimeStart());
					db.setTimeEnd(infoDO.getTimeEnd());
					schoolCurriculumInfoDao.updateSchoolCurriculumInfo(db);
				}else{
					if(isDateBetween(list, infoDO)){
						result.setDefaultErrorMsg("课时区间选择错误，存在同星期的一节课时间与你提交的时间冲突，请先更改冲突课节信息");
						return result;
					}
					schoolCurriculumInfoDao.insertSchoolCurriculumInfo(infoDO);
				}
			}
			result.setSuccess(true);
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.queryAllSchoolCurriculum catch a exception.",e);
		}
		return result;
	}
	
	private boolean isDateBetween(List<SchoolCurriculumInfoDO> list, SchoolCurriculumInfoDO infoDO ) {
		String start = "2013-05-01 "+infoDO.getTimeStart();
		String end = "2013-05-01 "+infoDO.getTimeEnd();
		Date s = CalendarUtil.toDate(start, "yyyy-MM-dd HH:mm");
		Date e = CalendarUtil.toDate(end, "yyyy-MM-dd HH:mm");
		
		for (SchoolCurriculumInfoDO curriculumInfoDO : list) {
			String ostart =  "2013-05-01 "+curriculumInfoDO.getTimeStart();
			String oend = "2013-05-01 "+curriculumInfoDO.getTimeEnd();
			
			Date os =  CalendarUtil.toDate(ostart, "yyyy-MM-dd HH:mm");
			Date oe = CalendarUtil.toDate(oend, "yyyy-MM-dd HH:mm");
			
			if(CalendarUtil.isDateBetween(s, os, oe)){
				return true;
			}
			if(CalendarUtil.isDateBetween(e, os, oe)){
				return true;
			}
		}
		return false;
	}
	
	private SchoolCurriculumInfoDO getSameLessionSection(
			List<SchoolCurriculumInfoDO> list, SchoolCurriculumInfoDO infoDO) {
		for (SchoolCurriculumInfoDO curriculumInfoDO : list) {
			if (curriculumInfoDO.getWeek().intValue() == infoDO.getWeek().intValue()
					&& infoDO.getLessionSection().intValue() == curriculumInfoDO.getLessionSection().intValue()) {
				return curriculumInfoDO;
			}
		}
		return null;
	}
	
	@Override
	public Result updateSchoolCurriculumInfo(SchoolCurriculumInfoDO infoDO) {
		Result result = new ResultSupport(false);
		try {
			checkArgs(infoDO,true);
			result.setSuccess(schoolCurriculumInfoDao.updateSchoolCurriculumInfo(infoDO));
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.queryAllSchoolCurriculum catch a exception.",e);
		}
		return result;
	}
	
	private void checkArgs(SchoolCurriculumDefinedDO definedDO){
		checkNotNull(definedDO);
		checkArgument(!isNullOrEmpty(definedDO.getClassName()));
		checkArgument(!isNullOrEmpty(definedDO.getDeptName()));
		checkArgument(!isNullOrEmpty(definedDO.getName()));
		checkArgument(definedDO.getSchoolId()!= null && definedDO.getSchoolId()>0);
		checkArgument(!isNullOrEmpty(definedDO.getDiyName()));
	}
	
	private void checkArgs(SchoolCurriculumInfoDO infoDO,boolean isUpdate) throws SQLException{
		checkNotNull(infoDO);
		checkArgument(!isNullOrEmpty(infoDO.getLession()));
		checkArgument(!isNullOrEmpty(infoDO.getTeacher()));
		checkArgument(!isNullOrEmpty(infoDO.getLocation()));
		checkArgument(!isNullOrEmpty(infoDO.getLession()));
		checkArgument(infoDO.getDefinedId() != null && infoDO.getDefinedId()>0);
		
		if(isUpdate){
			SchoolCurriculumDefinedDO definedDO = schoolCurriculumDefinedDao.getByDefinedId(infoDO.getDefinedId());
			checkNotNull(definedDO);
		}
		
		checkArgument(infoDO.getWeek() != null && infoDO.getWeek()>0 && infoDO.getWeek()<8);

//		String timeStart = infoDO.getTimeStart();
//		String timeEnd = infoDO.getTimeEnd();
//		checkArgument(!isTimeOutOf180Mins(timeStart, timeEnd), "课时区间设置过长.");
	}
	/**
	 * 1、时间间隔是否超过180分钟，我们认为正常的一节课不能超过这个时间
	 * 2、开始时间不能早于结束时间
	 */
	private boolean isTimeOutOf180Mins(String timeStart,String timeEnd){
		String start = "2013-05-01 "+timeStart;
		String end = "2013-05-01 "+timeEnd;
		
		Date s = CalendarUtil.toDate(start, "yyyy-MM-dd HH:mm");
		Date e = CalendarUtil.toDate(end, "yyyy-MM-dd HH:mm");

		if(CalendarUtil.AFTER == CalendarUtil.compareTwoDate(s, e)){
			return false;
		}
		
		int intevel = CalendarUtil.getTimeIntervalMins(s, e);
		
		return intevel > 180 || intevel<30;
	}

	@Override
	public Result queryAllSchoolCurriculumByUser(String name) {
		Result result = new ResultSupport(false);
		try {
			checkArgument(!isNullOrEmpty(name),"user id is required.");
			SchoolCurriculumDefinedDO definedDO = schoolCurriculumDefinedDao.getByUserNamed(name);
			if(definedDO != null){
				long definedId = definedDO.getId();
				
				List<SchoolCurriculumInfoDO> infoList = schoolCurriculumInfoDao.getSchoolCurriculumInfo(definedId);
				
				result.setDefaultModel(new SchoolCurriculum(definedDO, infoList));
				result.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.queryAllSchoolCurriculum catch a exception.",e);
		}
		return result;
	}

	@Override
	public SchoolCurriculumDefinedDO getByEmail(String email) {
		try {
			return schoolCurriculumDefinedDao.getByEmail(email);
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.doLogin catch a exception.",e);
		}
		return null;
	}

	@Override
	public SchoolCurriculumDefinedDO getSchoolCurriDefinedById(long id) {
		try {
			return schoolCurriculumDefinedDao.getByDefinedId(id);
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.doLogin catch a exception.",e);
		}
		return null;
	}

	@Override
	public boolean updateStudentPassword(String email, String ip,
			String password) {
		try {
			SchoolCurriculumDefinedDO definedDO = schoolCurriculumDefinedDao.getByEmail(email);
			if(definedDO == null)return false;
			definedDO.setPassword(password);
			definedDO.setStatus(1);
			return schoolCurriculumDefinedDao.updateSchoolCurriculumDefinedDO(definedDO);
		} catch (Exception e) {
			log.error("SchoolCurriculumAO.updateStudentPassword catch a exception.",e);
		}
		return false;
	}
	
}
